package com.mq.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.mq.domain.SysDept;
import com.mq.domain.SysUser;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 发送消息
 * @author gxd
 * @since 2025/6/8
 */
@Service
public class SendDataService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${mq.exchange-name}")
    private String exchangeName;

    @Value("${mq.user-route-key}")
    private String userRouteKey;

    @Value("${mq.dept-route-key}")
    private String deptRouteKey;

    private static final String YYYY_MM_dd = "yyyy-MM-dd";

    /**
     * 批次发送用户数据
     */
    public void sendUserData(List<SysUser> sysUsers) {
        sysUsers.forEach(user -> {
            user.setGroupId("1");
            user.setCreateTime(genRandomDate(user.getCreateTime()));
            rabbitTemplate.convertAndSend(exchangeName, userRouteKey, JSONUtil.toJsonStr(user));
        });
    }

    /**
     * 生成随机日期格式
     */
    private Date genRandomDate(Date date) {
        int num = RandomUtil.randomInt(1, 10);
        if(num < 6) {
            return DateUtil.parse(DateUtil.format(date, YYYY_MM_dd), YYYY_MM_dd);
        }
        return date;
    }

    /**
     * 批次发送部门数据
     */
    public void sendDeptData(List<SysDept> sysDepts) {
        sysDepts.forEach(dept -> {
            if (dept.getId() > 10 && dept.getId() < 21) {
                dept.setId((long) RandomUtil.randomInt(1, 10));
            }
            dept.setCreateTime(genRandomDate(dept.getCreateTime()));
            rabbitTemplate.convertAndSend(exchangeName, deptRouteKey, JSONUtil.toJsonStr(dept));
        });
    }
}
